
clear 
set more off

use "$data\cohabitation_2001.dta"  , clear
append using "$data\cohabitation_2011.dta" , force

*  Here select ITALY_YEAR !!!!

drop if hbc!=0 & hitaly_year<1997 & year==2001
drop if wbc!=0 & witaly_year<1997 & year==2001
drop if hbc!=0 & hitaly_year<2007 & year==2011
drop if wbc!=0 & witaly_year<2007 & year==2011
drop if hbc==0 & hitaly_year!=. & year==2011
drop if wbc==0 & witaly_year!=. & year==2011

* Recode province that change over time

rename provincia provres
recode provres ( 108 = 15) // change monza-brianza in MILANO
recode provres ( 110 = 72) // change barletta-andria-trani e foggia in BARI 
recode provres  ( 71 = 72)  
recode provres ( 91 = 92 ) // change oristano, nuoro, olbia-tempio, ogliastra, medio-campidano, carbonia-iglesias in CAGLIARI
recode provres ( 95 = 92 )
recode provres ( 104 = 92 )
recode provres ( 105 = 92 )
recode provres ( 106 = 92 )
recode provres ( 107 = 92 )
recode provres ( 99 = 41) // change rimini in pesaro
recode provres ( 109 = 44) // change fermo in ascoli-piceno

* Recode nationalities that change over time

recode hbc (270 = 224 ) // Serbia e Montenegro insieme
recode hbc (271 = 224 )
recode wbc (270 = 224 ) // Serbia e Montenegro insieme
recode wbc (271 = 224 )
drop if hnationality==3
drop if wnationality==3

* Generate family types

codebook hbc 
codebook wbc
gen HOM = hbc==wbc
lab var HOM "Homogamous"
gen HET = HOM!=1
lab var HET "Heterogamous"
gen HET_IT =  (hbc==0 & wbc>0) | ( hbc>0 & wbc==0) 
lab var HET_IT "Heterogamous-Italian"

* Generate n. of cohabitaions

gen couple=1
lab var couple "cohabitations"
collapse (sum) couple , by( provres year wbc hbc)
preserve
rename couple nm
gen type= "cohab"
save "$data\cohabitations_tomerge.dta", replace
restore

* Merge with Singles 

merge m:1 provres hbc year using "$data\Msingle_cohabitation_FINAL.dta" , keep(match master) keepusing(Msingle)
tab _merge
drop _merge 

merge m:1 provres wbc year using "$data\Fsingle_cohabitation_FINAL.dta" , keep(match master) keepusing(Fsingle)
tab _merge
drop _merge 

merge m:1 provres using "$data\population_byprovince.dta" , keep(match master) 
tab _merge
drop _merge


* Generate gains from cohabitaion

collapse (sum) couple  (mean) Fsingle Msingle , by(  provres year wbc hbc population)
gen phixy = ln((couple^2)/(Fsingle*Msingle))

save "$data\Gain_cohabitation_robust.dta" , replace



